import { useAtomValue } from "jotai";
import Markdown from "markdown-to-jsx";
import { useEffect, useMemo } from "react";
import { useSearchParam } from "shared/hooks";
import { LoadingBarScale, Question } from "shared/icons";
import { Button, Popover } from "shared/components";
import ModelSelector from "@/components/ModelSelector";
import useQuery from "@/lib/hooks/useQuery";
import currentModelAtom from "@/store/currentModel";
import TypeSelector from "@/components/TypeSeletor";
import currentTypeAtom from "@/store/currentType";
import ArrowRightUp from "@/assets/icons/ArrowRightUp";

export default function Home() {
  const uri = useSearchParam(
    "uri",
    "http://data.library.sh.cn/gj/resource/instance/hame7w71trs11lc3",
  );
  const model = useAtomValue(currentModelAtom);
  const type = useAtomValue(currentTypeAtom);
  const { data, error, loading, query, cancel } = useQuery<{
    code: number;
    summary: string;
    source: string[];
  }>({
    model: type === 2 ? undefined : (model as string),
    url: uri,
    type: type as number,
  });

  useEffect(() => {
    query();
    return cancel;
  }, []);

  const markdown = useMemo(() => {
    if (!data?.summary) {
      return null;
    }
    return data.summary.replace(
      /\[{1,2}citation:(\d+)\]{1,2}/g,
      (match, $1) => {
        return `<slot data-citation='${$1}'/>`;
      },
    );
  }, [data?.summary]);

  return (
    <>
      <h1 className="mb-12 mt-6 text-center text-3xl font-bold">
        AI 書誌(beta)
      </h1>
      <div className="flex flex-wrap items-center gap-x-6 gap-y-2">
        <ModelSelector />
        <TypeSelector />
        <Button
          loading={loading}
          disabled={loading || !uri}
          onClick={() => query()}
        >
          {loading ? "正在生成" : "重新生成"}
        </Button>
      </div>
      {error && (
        <div className="mt-4 rounded border border-red-500 bg-red-200 p-4">
          {error.message}
        </div>
      )}
      {loading && (
        <div className="flex items-center justify-center py-10">
          <LoadingBarScale height="2em" width="2em" />
        </div>
      )}
      {markdown && (
        <>
          <div className="my-4 text-right text-sm">
            <a
              href={`https://gj.library.sh.cn/evidenceBased/instance#uri=${uri}&type=1`}
              className="inline-flex items-center text-blue-500 hover:text-blue-300"
              target="_blank"
            >
              <span>循證研究</span>
              <ArrowRightUp />
            </a>
          </div>
          <div className="markdown-body !mt-8">
            <Markdown
              options={{
                renderRule(next, node, renderChildren, state) {
                  if (
                    "tag" in node &&
                    node.tag === "slot" &&
                    "data-citation" in node.attrs
                  ) {
                    return (
                      <Popover
                        trigger={
                          <button className="mx-2 inline-flex items-center text-blue-500 hover:text-blue-400">
                            <span className="mr-1">
                              {node.attrs["data-citation"] as string}
                            </span>
                            <Question height="0.8em" width="0.8em" />
                          </button>
                        }
                        contentClassName="max-h-[50dvh] max-w-[80dvw] overflow-auto text-sm"
                      >
                        <pre>
                          {
                            data?.source[
                              Number(node.attrs["data-citation"]) - 1
                            ]
                          }
                        </pre>
                      </Popover>
                    );
                  }
                  return next();
                },
              }}
            >
              {markdown}
            </Markdown>
          </div>
        </>
      )}
    </>
  );
}
